var App = {
	context: null,
	ready: [],
	js: [],

	init: function( context )
	{
		this.context = context;

		$(document).ready( function() {
			eval("if ( typeof App.preExecute == 'function' ) App.preExecute();");
			for ( var i = 0; i < App.ready.length; i++ ) App.ready[i]();
		} );

		this.executeAction(this.context.action);

		$('body').ajaxComplete(function(e, xhr, ops) {
			if ( !xhr ) return;

			var response = xhr.responseText;
			if ( response.indexOf('class="exception"') > 0 )
			{
				App.showException( response );
				return false;
			}

			if ( typeof xhr.getResponseHeader == 'undefined' ) return;

			if ( xhr.getResponseHeader('X-REDIRECT') )
				document.location = xhr.getResponseHeader('X-REDIRECT');
		});
	},

	executeAction: function(action_name)
	{
		var action = this.getActionHandler(action_name);

		$(document).ready( function() {
			eval("if ( typeof " + action + " == 'object' ) " + action + ".execute();");
		} );
	},

	getActionHandler: function( action )
	{
		action = action.replace(/_/g, ' ');
		action = action.replace(/^(.)|\s(.)/g, function ($1) {
			return $1.toUpperCase();
		}) + 'Action';

		return action.replace(/ /g, '');
	},

	depend: function( callback, js )
	{
		$.getScript(js, function() {
			callback();
			App.js.push(js);
		});
	},

	setParam: function( name, value )
	{
		document.location = '#' + name + '=' + value;
	},

	getParam: function( name )
	{
		if ( document.location.href.indexOf('#') == -1 ) return null;

		var query = document.location.href.substr(document.location.href.indexOf('#') + 1);
		var vars = query.split("&");

		for ( var i = 0; i < vars.length; i++ )
		{
			var pair = vars[i].split("=");
			if ( pair[0] == name ) return pair[1];
		}

		return null;
	},
	
	cookie: function (key, value, options) {
		// key and value given, set cookie...
		if (arguments.length > 1 && (value === null || typeof value !== "object")) {
			options = jQuery.extend({}, options);

			if (value === null) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			return (document.cookie = [
				encodeURIComponent(key), '=',
				options.raw ? String(value) : encodeURIComponent(String(value)),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
		}

		// key and possibly options given, get cookie...
		options = value || {};
		var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
		return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
	}
}